import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from 'src/database/prisma.service';
import { CreatePlatformDto } from './dto/create-platform.dto';
import { TaskService } from 'src/task/task.services';

@Injectable()
export class PlatformService {
  constructor(
    private readonly prismaServer: PrismaService,
    private readonly taskServer: TaskService,
  ) {}
  async create(platform: CreatePlatformDto) {
    Logger.log(`create platform ${platform.name}`);
    const p = await this.prismaServer.platform.create({ data: platform });
    return p;
  }
  async delete(platformId: number) {
    Logger.log(`delete platform ${platformId}`);
    await this.prismaServer.$transaction(async (prisma) => {
      const taskPlatforms = await prisma.taskPlatform.findMany({
        where: { platformId },
      });
      for (const tp of taskPlatforms) {
        await this.taskServer.removePlatformFromTask(tp.taskId, platformId); // Unlink
      }
      await prisma.cookie.deleteMany({ where: { platformId } });
      return await prisma.platform.delete({ where: { id: platformId } });
    });
  }
  async getPlatform(id: number) {
    Logger.log(`get platform ${id}`);
    return await this.prismaServer.platform.findFirst({ where: { id: id } });
  }
  async getPlatforms(ids: number[]) {
    return await this.prismaServer.platform.findMany({
      where: { id: { in: ids } },
    });
  }
  async getAllPlatforms() {
    return await this.prismaServer.platform.findMany({});
  }
}
